<template>
  <div class="palyArea">
    <div class="areaLeft">
      <div class="areaInfo">
        <div>
          <div class="title">
            <div
              class="liveSatus"
              :class="{
                statusIng: detailsData.status === 'START',
                statusEnd: detailsData.status === 'END',
              }"
            >
              <div v-if="detailsData.status === 'START'"></div>
              {{ statusArr[detailsData.status].txt }}
            </div>
            {{ detailsData?.name }}
          </div>
          <div class="other">
            <div class="look" v-if="liveIng">
              <img src="" alt="" srcset="" />
              {{ currentUserNum }} 人学习
            </div>
            <div class="type">分类：{{ detailsData.categoryName }}</div>
          </div>
        </div>
        <div class="areaRgtBtn">
          <!-- <CustomButton
            class="customBtn"
            type="primary"
            @click="mobileLookLive"
          >
            手机端观看
          </CustomButton> -->
          <CustomButton
            v-if="isCreateUser"
            class="customBtn"
            type="primary"
            @click="lookLiveInfo"
          >
            查看直播信息
          </CustomButton>
        </div>
      </div>
      <div class="areaPlay">
        <div class="videoArea">
          <!-- 未开始 -->
          <div
            v-if="detailsData.status === 'NO_START' || isGenerate"
            class="videoPlay"
          >
            <img
              :src="$getImageUrl(detailsData.originImg)"
              alt=""
              srcset=""
            />
          </div>
          <!-- 直播中 -->
          <div
            v-if="detailsData.status === 'START'"
            id="livePlayer"
            class="videoPlay"
          ></div>
          <!-- 文档模块 -->
          <div v-if="detailsData.status === 'START'" id="drawPanel" style="width: 0; height: 0; display: none;"></div>

          <!-- 回放 视频模块 -->
          <div
            v-if="!isGenerate && detailsData.status === 'END'"
            id="playbackPlayer"
            class="videoPlay"
          ></div>
          <!-- 文档模块 -->
          <div v-if="!isGenerate && detailsData.status === 'END'" id="playbackPanel" style="width: 0; height: 0; display: none;"></div>
          
          <div class="lockArea" v-if="isGenerate">回放生成中</div>
        </div>
        <div class="option">
          <div class="optionLeft">
            <div class="optionItem" @click="setVoteCourseFn">
              <img
                v-if="!isVote"
                src="@/assets/like_icon.png"
                alt=""
                srcset=""
              />
              <img
                v-if="isVote"
                src="@/assets/like_select.png"
                alt=""
                srcset=""
              />
              <span>{{ likes }}</span>
            </div>
            <div class="optionItem" @click="setFavCourseFn">
              <img
                v-if="!isFav"
                src="@/assets/collect_icon.png"
                alt=""
                srcset=""
              />
              <img
                v-if="isFav"
                src="@/assets/collect_select.png"
                alt=""
                srcset=""
              />
            </div>
            <div class="optionItem">
              <el-popover
                placement="bottom-start"
                width="400"
                trigger="hover"
              >
                <div class="relayArea">
                  <el-input
                    ref="inputToCopy"
                    v-model="textToCopy"
                    readonly
                    placeholder="这里将显示要复制的文本"
                  ></el-input>
                  <el-button type="primary" @click="copyToClipboard">复制链接</el-button>
                </div>
                <img
                  src="@/assets/relay.png"
                  alt=""
                  srcset=""
                  slot="reference"
                />
              </el-popover>
            </div>
          </div>
          <div class="optionRgt">
            <el-popover
              placement="bottom"
              width="150"
              trigger="hover"
            >
              <div class="qrCodeBox">
                <canvas ref="qrcodeCanvas"></canvas>
              </div>
              <div slot="reference">
                <img class="moreImg" src="@/assets/mbCode.png" alt="" srcset="" />
              </div>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
    <div class="areaRgt">
      <div class="areaUser">
        <!-- <img class="userHead" src="@/assets/footerBg.png" alt="" srcset="" /> -->
        <div class="userInfo">
          <div class="name">{{ detailsData?.promoter }}</div>
          <!-- <div class="info">湖北省优秀教师、武汉市优秀教师</div> -->
        </div>
      </div>
      <div class="areaDiscuss">
        <div class="chatRoom">
          <div class="roomInfo">
            <div class="title">讨论区</div>
            <div class="notice">
              <img src="@/assets/notice.png" alt="" srcset="" />
              直播公告
            </div>
            <div class="noticeContent">
              {{ noticeContent }}
            </div>
          </div>
          <div class="msgArea">
            <div style="flex: 1"></div>
            <div
              class="userCard"
              v-for="(item, index) in chatMsgList"
              :key="index"
            >
              <img
                v-if="item.useravatar"
                class="userHead"
                :src="item.useravatar"
                alt=""
                srcset=""
              />
              <div class="userInfo">
                <div class="info">
                  {{ item.username }}
                  <span v-if="liveIng">{{ item.time }}</span>
                </div>
                <div class="name">{{ item.msg }}</div>
              </div>
            </div>
          </div>
          <div class="sendComment">
            <el-input
              class="textarea"
              type="textarea"
              :rows="3"
              resize="none"
              placeholder="请输入内容"
              v-model="comment"
              :disabled="!liveIng"
            />
            <CustomButton
              class="customButton"
              type="primary"
              :disabled="!comment"
              @click="sendComment"
            >
              发送
            </CustomButton>
          </div>
        </div>
      </div>
    </div>
    <LiveInfo ref="LiveInfo" :objectId="detailsData?.objectId"></LiveInfo>
    <!-- <QRCode v-if="roomId" ref="QRCode" :roomId="roomId" :title="detailsData?.name"></QRCode> -->
  </div>
</template>

<script>
import CustomButton from '@/components/CustomButton';
import * as common from '@/utils/livePlay';
import { getUserInfo, getToken } from '@/utils/auth';
import {
  voteCourse,
  getVoteStatusById,
  unVoteCourse,
  getFavStatusById,
  favCourse,
  unFavCourse,
  getLikesCountById
} from '@/api/course';
import { copyToClipboard } from '@/utils'
import LiveInfo from '@/components/LiveInfo.vue';
import { toLogin } from '@/utils/baseConfig';
import QRCode from 'qrcode';

export default {
  name: 'PalyArea',
  components: { CustomButton, LiveInfo },
  props: {
    detailsData: {
      type: Object,
      default: null,
    },
    queryParams: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      statusArr: {
        NO_START: {
          txt: '未开始',
        },
        START: {
          txt: '直播中',
        },
        END: {
          txt: '已结束',
        },
      },
      isVote: false,
      isFav: false,
      textToCopy: window.location.href,
      likes: 0,
      activeName: 'schedule',
      recordId: null, // 当前回放id
      roomId: null, // roomId
      comment: null, // 评论内容
      isGenerate: false, // 是否回放生成中
      chatMsgList: [], // 聊天信息列表
      currentUserNum: 0, // 当前在线人数
      noticeContent: '暂无公告',
    };
  },
  computed: {
    useData() {
      const recordList =
        (this.detailsData?.teachDetailList?.length &&
          this.detailsData?.teachDetailList[0].recordList) ||
        [];
      if (!recordList.length) {
        return [];
      }
      return recordList;
    },
    // 是否是发起人
    isCreateUser() {
      return getUserInfo()?.objectId === this.detailsData?.creater
    },
    isLogin() {
      return !!getToken();
    },
    // 是否在直播中
    liveIng() {
      return this.detailsData?.status === 'START' || false;
    },
  },
  created() {},
  mounted() {
    this.initLiveSDK();
    this.getVoteStatusById();
    this.getFavStatusById();
    this.getLikesCountById();
  },
  beforeDestroy() {
    if(this.detailsData.status === 'START') {
      console.log('直播销毁：', window.DWLive)
      window.DWLive.destroy()
    }
    if (this.detailsData.status === 'END') {
      console.log('回放销毁：', window.$.DW)
      window.$.DW.destroy();
    }
  },
  methods: {
    // 初始化视频
    initLiveSDK() {
      this.$nextTick(() => {
        if (this.detailsData.teachDetailList?.length) {
          this.roomId = this.detailsData?.teachDetailList[0].roomId;
          this.generateQRCode()
          // 如果直播中
          if (this.detailsData.status === 'START') {
            this.createdLive();
          }
          if (this.detailsData.status === 'END') {
            this.recordId =
              this.detailsData?.teachDetailList[0].recordList[0].recordId;
            this.createdLiveBack();
          }
        }
      });
    },
    // 创建直播
    createdLive() {
      console.log('直播initSdk');
      common.initSdk({
        roomid: this.roomId,
        viewername: getUserInfo()?.name,
      });
      // 直播监听init
      this.liveInit()
    },
    liveInit() {
      const that = this;
      // 直播接收消息
      window.DWLive.onPublicChatMessage = function (data) {
        console.log('onPublicChatMessage', JSON.parse(data));
        let useData = that.chatMsgList;
        useData.push(JSON.parse(data));
        that.chatMsgList = useData;
      };
      // 公告
      window.DWLive.onAnnouncementShow = function (data) {
        that.noticeContent = data;
      };
      window.DWLive.onAnnouncementRelease = function (data) {
        that.noticeContent = data;
      };
      window.DWLive.onAnnouncementRemove = function () {
        that.noticeContent = '暂无公告';
      };
      // 直播获取在线人数
      window.DWLive.onUserCountMessage = function (data) {
        that.currentUserNum = data;
      };
      // 直播开始
      window.DWLive.onLiveStart = function () {
        console.log('onLiveStart', that.isLogin)
        if(!that.isLogin) {
          return toLogin();
        }
      };
      // 登录成功
      window.DWLive.onLoginSuccess = function(data) {
        console.log("websdk log: DWLive.onLoginSuccess", data);
        window.DWLive.groupId = data.viewer.groupId;
      };
      // 卡顿质量日志
      window.DWLive.onLiveInteractionNetworkQuality = function(netData) {
        console.log('websdk log: DWLive.onLiveInteractionNetworkQuality', netData)
        console.log("卡顿质量日志：", netData)
      };
      // socket链接成功回调
      window.onSocketConnect = function() {
        console.log('websdk log: window.onSocketConnect')
        console.log("pusher链接成功");
      };
      // socket链接断开回调
      window.onSocketDisconnect = function() {
        console.log('websdk log: window.onSocketDisconnect')
      }
      // 断流回调监听
      window.cc_player_stream_disconnect = function() {
        console.log('websdk log: window.cc_player_stream_disconnect')
        console.log('断流回调监听到了~断流回调监听到了~PC端')
      };
      // 卡顿了
      window.cc_player_stream_waiting = function() {
        console.log('websdk log: window.cc_player_stream_waiting')
        console.log('卡顿了-----')
      };
    },
    // 直播发送消息
    sendComment() {
      window.DWLive.sendPublicChatMsg(this.comment);
      this.comment = '';
    },
    // 创建回放
    createdLiveBack() {
      if (!this.recordId) {
        this.isGenerate = true;
        return;
      }
      this.isGenerate = false;
      common.initBackSdk({
        roomid: this.roomId,
        recordId: this.recordId,
        viewername: getUserInfo()?.name,
      });
      this.initBack()
    },
    // 监听回放
    initBack() {
      const that = this;
      // 获取消息列表
      window.on_cc_live_chat_msg = function (data) {
        let useData = that.chatMsgList;
        useData.push(data);
        that.chatMsgList = useData;
      }
      window.on_player_start = function () {
        console.log('on_player_start', that.isLogin)
        if(!that.isLogin) {
          return toLogin();
        }
      }
      window.on_cc_live_player_load = function () {
        document.querySelector('video').addEventListener('contextmenu', function(e) {
          e.preventDefault();
        });
      }
    },

    // 获取点赞数
    async getLikesCountById() {
      try {
        let params = {
          courseId : this.detailsData.objectId,
        };
        const resData = await getLikesCountById(params);
        this.likes = resData;
      } catch (error) {
        console.error(error);
      }
    },

    // 获取是否已经点赞
    async getVoteStatusById() {
      try {
        let params = {
          courseId : this.detailsData.objectId,
        };
        const resData = await getVoteStatusById(params);
        this.isVote = resData;
      } catch (error) {
        console.error(error);
      }
    },
    // 课程点赞
    async setVoteCourseFn() {
      if(!this.isLogin) {
        return toLogin();
      }
      try {
        let params = {
          courseId : this.detailsData.objectId,
        };
        if(this.isVote) {
          await unVoteCourse(params);
          this.isVote = false;
          this.likes = this.likes - 1;
        } else {
          await voteCourse(params);
          this.isVote = true;
          this.likes = this.likes + 1;
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 获取是否已经收藏
    async getFavStatusById() {
      try {
        let params = {
          courseId : this.detailsData.objectId,
        };
        const resData = await getFavStatusById(params);
        this.isFav = resData;
      } catch (error) {
        console.error(error);
      }
    },

    // 课程收藏
    async setFavCourseFn() {
      if(!this.isLogin) {
        return toLogin();
      }
      try {
        let params = {
          courseId : this.detailsData.objectId,
        };
        if(this.isFav) {
          await unFavCourse(params);
          this.isFav = false;
        } else {
          await favCourse(params);
          this.isFav = true;
        }
      } catch (error) {
        console.error(error);
      }
    },

    copyToClipboard() {
      copyToClipboard(this.textToCopy);
    },
    // 查看直播信息
    lookLiveInfo() {
      this.$refs.LiveInfo.dialogVisible = true;
    },
    // 手机端观看二维码
    mobileLookLive() {
      this.$refs.QRCode.dialogVisible = true;
    },
    generateQRCode() {
      this.$nextTick(() => {
        const url = `${window.location.origin}/h5Live?roomId=${this.roomId}&title=${this.detailsData.name}`; // 二维码的链接
        const qrcodeCanvas = this.$refs.qrcodeCanvas;
        QRCode.toCanvas(qrcodeCanvas, url, {
          width: 150,
          height: 150
        }, function (error) {
          if (error) {
            console.error(error);
          } else {
            console.log('二维码生成成功！');
          }
        });
      })
    }
  },
};
</script>
<style lang="scss" scoped>
.palyArea {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  .areaLeft {
    width: 1026px;
    .areaInfo {
      width: 1026px;
      height: 109px;
      padding-top: 24px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .areaRgtBtn {
        display: flex;
        align-items: center;
      }
      .customBtn {
        padding: 10px 12px;
        margin-left: 16px;
      }
      ::v-deep .customBtn.el-button span {
        margin-left: 0;
      }
      .title {
        height: 28px;
        display: flex;
        align-items: center;
        color: $text-title-color;
        font-size: 20px;
        font-weight: 600;

        .liveSatus {
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 10px;
          font-weight: 600;
          line-height: 14px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 8px;
          background: #24d82c;

          div {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: #fff;
            margin-right: 4px;
          }
        }

        .statusIng {
          background: $primary-color;
        }

        .statusEnd {
          background: $text-color-secondary;
        }
      }
      .other {
        display: flex;
        align-items: center;
        margin-top: 8px;
        .look {
          font-size: 14px;
          font-weight: 400;
          color: $text-color;
          margin-right: 24px;
        }
        .type {
          font-size: 14px;
          font-weight: 400;
          line-height: 21px;
        }
      }
    }
    .areaPlay {
      width: 1026px;
      .videoArea {
        position: relative;
        width: 100%;
        height: 700px;
        background: #000;
        .lockArea {
          position: absolute;
          width: 100%;
          height: 700px;
          background: rgba(0, 0, 0, 0.8);
          z-index: 9;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          top: 0;
          left: 0;
        }
        .videoPlay {
          width: 100%;
          height: 700px;
          position: relative;
          z-index: 8;
          display: flex;
          justify-content: center;
          align-items: center;
          overflow: hidden;
          img {
            width: 100%;
            height: 768px;
            object-fit: cover;
          }
        }
      }
      .option {
        height: 68px;
        padding: 0 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #fff;
        box-shadow: $box-shadow;
        border-radius: 0 0 8px 8px;
        .optionLeft {
          display: flex;
          align-items: center;
          .optionItem {
            display: flex;
            align-items: center;
            cursor: pointer;
            margin-right: 24px;
            font-size: 14px;
            font-weight: 400;
            span {
              width: 6px;
            }
            img {
              width: 28px;
              height: 28px;
              margin-right: 8px;
            }
          }
        }
        .optionRgt {
          .moreImg {
            width: 28px;
            height: 28px;
          }
        }
      }
    }
  }
  .areaRgt {
    width: 326px;
    .areaUser {
      width: 100%;
      height: 109px;
      padding-top: 33px;
      box-sizing: border-box;
      display: flex;
      .userHead {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        margin-right: 12px;
      }
      .userInfo {
        .name {
          font-size: 20px;
          font-weight: 600;
          line-height: 28px;
          color: $text-title-color;
        }
        .info {
          margin-top: 4px;
          font-size: 14px;
          font-weight: 400;
          line-height: 20px;
          color: $text-color;
        }
      }
    }

    .areaDiscuss {
      width: 326px;
      height: 768px;
      box-shadow: $box-shadow;
      background: #fff;
      border-radius: 8px;
      .chatRoom {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        .roomInfo {
          width: 100%;
          height: 144px;
          padding: 16px;
          box-sizing: border-box;
          .title {
            font-size: 16px;
            font-weight: 600;
            line-height: 22px;
            color: $text-title-color;
          }
          .notice {
            width: 70px;
            height: 18px;
            padding: 2px 6px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            background: linear-gradient(90deg, #afd1fa 0%, #ffffff 100%);
            font-size: 10px;
            box-sizing: border-box;
            margin-top: 12px;
            white-space: nowrap;
            img {
              width: 14px;
              height: 14px;
              margin-right: 4px;
            }
          }
          .noticeContent {
            width: 100%;
            overflow-y: auto;
            margin-top: 8px;
            font-size: 12px;
            font-weight: 400;
            line-height: 18px;
          }
        }
        .msgArea {
          flex: 1;
          background: $page-background-color;
          height: 499px;
          overflow-y: auto;
          padding: 16px 0;
          display: flex;
          flex-direction: column;
          .userCard {
            width: 100%;
            height: 36px;
            margin-bottom: 20px;
            padding: 0 16px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column; /* 新消息在底部 */
            justify-content: flex-end; /* 内容在交叉轴的末端（即垂直滚动时的底部） */
            .userHead {
              width: 36px;
              height: 36px;
              border-radius: 50%;
              margin-left: 8px;
            }
            .userInfo {
              .info {
                color: $text-color;
                font-size: 12px;
                font-weight: 400;
                span {
                  margin-left: 6px;
                  font-size: 12px;
                  color: $text-color-secondary;
                }
              }
              .initiator {
                width: 38px;
                height: 16px;
                border-radius: 2px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: $text-color-primary;
                background: #d7e8fc;
                font-size: 10px;
              }
              .name {
                color: $text-title-color;
                margin-top: 6px;
                font-size: 14px;
                font-weight: 400;
                line-height: 16px;
              }
            }
          }
        }
        .sendComment {
          width: 100%;
          height: 125px;
          background: #fff;
          padding: 13px 16px 0;
          box-sizing: border-box;
          .textarea {
            width: 294px;
            height: 56px;
            ::v-deep .el-textarea__inner {
              width: 294px;
              height: 56px;
              padding: 10px;
              box-sizing: border-box;
              border: none;
              line-height: 20px;
              font-size: 14px;
              font-weight: 400;
              background: #fff;
              color: $text-color-secondary;
              border: 1px solid #c6c6c6;
            }
          }
          .customButton {
            padding: 5px 32px;
            margin-top: 12px;
            float: right;
          }
        }
      }
    }
  }
}

.relayArea {
  display: flex;
  padding: 20px;
  box-sizing: border-box;
}
.qrCodeBox {
  width: 100%;
  text-align: center;
}
</style>
